#! /usr/bin/env bash

cd "$(dirname "$0")"
cd ..

log=$(echo $0 | sed s/\.sh$//).log
if [ -f "$log" ]
then
	rm "$log"
fi

scan=$(ls -1 -v --reverse scan/????/??/??/??/??/??-??.csv | head --lines 1)
selection=$(echo $scan | sed s/\.csv$/-wep.csv/)
reverse=$(echo $scan | sed s/\.csv$/-wep-reverse.csv/)

if [ ! -f "$selection" ]
then
	tr --delete '\000' < "$scan" |\
	awk -F ',' '$7~/WEP/' |\
	sort --field-separator=, --general-numeric-sort --reverse --key=11 --reverse --key=10 --key=9 > "$selection"
fi

if [ ! -f "$reverse" ]
then
	tac "$selection" > "$reverse"
fi

while read line
do
	bssid=$(echo $line | awk -F', ' '{print $1}')
	channel=$(echo $line | awk -F', ' '{print $4}')
	essid="$(echo $line | awk -F', ' '{print $14}')"

	identifier=$(echo $bssid | tr '[A-Z]' '[a-z]' | tr --delete ':')
	if [ ! -z "$essid" ]
	then
		identifier=$identifier-$(echo $essid | tr '[A-Z]' '[a-z]' | tr --complement --delete '[a-z0-9]')
	fi

	if [[ ( -f capture/$identifier/key.txt ) || ( $channel -le 0 ) && ( 14 -ge $channel ) ]]
	then
		if [ -z "$essid" ]
		then
			echo $(date +"%Y-%m-%d %H:%M:%S") Ignoring BSSID $bssid channel $channel
		else
			echo $(date +"%Y-%m-%d %H:%M:%S") Ignoring BSSID $bssid channel $channel ESSID \"$essid\"
		fi
	fi
done < "$selection"

count=0
while read line
do
	bssid=$(echo $line | awk -F', ' '{print $1}')
	channel=$(echo $line | awk -F', ' '{print $4}')
	essid="$(echo $line | awk -F', ' '{print $14}')"
	score=$(echo $line | awk -F', ' '{printf "data %d beacon %d power %d", $11, $10, $9}')

	identifier=$(echo $bssid | tr '[A-Z]' '[a-z]' | tr --delete ':')
	if [ ! -z "$essid" ]
	then
		identifier=$identifier-$(echo $essid | tr '[A-Z]' '[a-z]' | tr --complement --delete '[a-z0-9]')
	fi

	if [[ ( ! -f capture/$identifier/key.txt ) && ( 0 -lt $channel ) && ( $channel -lt 14 ) ]]
	then
		count=$(($count + 1))
		if [ -z "$essid" ]
		then
			echo $(date +"%Y-%m-%d %H:%M:%S") Found BSSID $bssid $score channel $channel
		else
			echo $(date +"%Y-%m-%d %H:%M:%S") Found BSSID $bssid $score channel $channel ESSID \"$essid\"
		fi
	fi
done < "$reverse"

channel=
while read line
do
	bssid=$(echo $line | awk -F', ' '{print $1}')
	channel=$(echo $line | awk -F', ' '{print $4}')
	essid="$(echo $line | awk -F', ' '{print $14}')"

	identifier=$(echo $bssid | tr '[A-Z]' '[a-z]' | tr --delete ':')
	if [ ! -z "$essid" ]
	then
		identifier=$identifier-$(echo $essid | tr '[A-Z]' '[a-z]' | tr --complement --delete '[a-z0-9]')
	fi

	if [[ ( ! -f capture/$identifier/key.txt ) && ( 0 -lt $channel ) && ( $channel -lt 14 ) ]]
	then
		break
	else
		channel=
	fi
done < "$selection"

if [[ ( ! -z "$channel" ) && ( ! -z "$bssid" ) ]]
then
	echo $count, $bssid, $channel, "$essid" > "$log"
fi

